<template>
  <div class="mod-user">
    <div class="search-bar">
      <el-form
        @submit.native.prevent
        :inline="true"
        class="search-form"
        ref="searchForm"
        :model="searchForm"
        size="small"
        label-width="80px"
      >
        <div class="input-row">
          <el-form-item prop="activityName" label="活动名称:">
            <el-input
              v-model="searchForm.activityName"
              type="text"
              clearable
              placeholder="请输入活动名称"
            ></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="促销类型:">
            <el-select
              v-model="searchForm.activityMarketTypeId"
              clearable
              placeholder="请选择促销类型"
            >
              <el-option
                v-for="item in useTypes"
                :key="item.id"
                :label="item.activityTypeName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="activityOnlineState" label="状态:">
            <el-select
              v-model="searchForm.activityOnlineState"
              clearable
              placeholder="请选择状态"
            >
              <el-option
                v-for="item in [
                  { label: '进行中', value: '0' },
                  { label: '待开始', value: '1' },
                  { label: '已下架', value: '2' },
                  { label: '已结束', value: '3' },
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="activityBusinessState" label="活动类型:">
            <el-select
              v-model="searchForm.activityBusinessState"
              clearable
              placeholder="请选择活动类型"
            >
              <el-option
                v-for="item in [
                  { label: '平台活动', value: '1' },
                  { label: '商户活动', value: '2' },
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动时间:">
            <div class="flex">
              <el-radio-group
                v-model="searchForm.activityTimeState"
                @change="changeActivityTimeState"
              >
                <el-radio-button label="2">按时间</el-radio-button>
                <el-radio-button label="1">按周期</el-radio-button>
              </el-radio-group>
              <el-date-picker
                v-if="searchForm.activityTimeState == '2'"
                size="small"
                v-model="timer"
                type="datetimerange"
                :range-separator="$t('date.tip')"
                value-format="yyyy-MM-dd HH:mm:ss"
                :start-placeholder="$t('text.startTime')"
                :end-placeholder="$t('date.end')"
                :default-time="['00:00:00', '23:59:59']"
                @change="createTimeChange"
              ></el-date-picker>
              <div v-if="searchForm.activityTimeState == '1'">
                <div class="period-panel">
                  <el-form-item prop="name">
                    <el-radio-group
                      @change="changeActivityTimeCycleState"
                      v-model="searchForm.activityTimeCycleState"
                    >
                      <div class="period-line">
                        <el-radio label="0">每天</el-radio>
                        <el-time-picker
                          size="medium"
                          :disabled="searchForm.activityTimeCycleState != '0'"
                          is-range
                          v-model="timePickerValueByDay"
                          value-format="HH:mm:ss"
                          @change="changeTimePickerByDay"
                          range-separator="——"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          placeholder="选择时间范围"
                        >
                        </el-time-picker>
                      </div>
                      <div class="period-line">
                        <el-radio label="1">每周</el-radio>
                        <div class="week-list">
                          <el-checkbox-group
                            :disabled="searchForm.activityTimeCycleState != '1'"
                            size="medium"
                            v-model="checkboxGroups"
                            @change="changeCheckboxGroups"
                          >
                            <el-checkbox-button
                              v-for="week in useWeeks"
                              :label="week.value"
                              :key="week.value"
                              >{{ week.label }}</el-checkbox-button
                            >
                          </el-checkbox-group>
                          <el-time-picker
                            class="time-picker-3 time-picker-3-week"
                            value-format="HH:mm:ss"
                            :disabled="searchForm.activityTimeCycleState != '1'"
                            size="medium"
                            is-range
                            v-model="timePickerValueByMonth"
                            @change="changeTimePickerByMonth"
                            range-separator="——"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            placeholder="选择时间范围"
                          >
                          </el-time-picker>
                        </div>
                      </div>
                      <div class="period-line">
                        <el-radio label="2">每月</el-radio>
                        <div>
                          <el-select
                            size="medium"
                            v-if="searchForm.activityTimeCycleState == '2'"
                            v-model="searchForm.activityTimeMonthNum"
                            clearable
                            placeholder="请选择日期"
                          >
                            <el-option
                              v-for="item in useDays"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            ></el-option>
                          </el-select>

                          <el-select
                            disabled
                            size="medium"
                            v-if="searchForm.activityTimeCycleState != '2'"
                            v-model="searchForm._activityTimeMonthNum"
                            clearable
                            placeholder="请选择一个或者多个日期"
                          >
                            <el-option
                              v-for="item in useDays"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            ></el-option>
                          </el-select>

                          <el-time-picker
                            :disabled="searchForm.activityTimeCycleState != '2'"
                            class="time-picker-3"
                            value-format="HH:mm:ss"
                            size="medium"
                            is-range
                            v-model="timePickerValueByWeek"
                            @change="changeTimePickerByWeek"
                            range-separator="——"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            placeholder="选择时间范围"
                          >
                          </el-time-picker>
                        </div>
                      </div>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="default-btn primary-btn" @click="searchChange(true)">
              {{ $t("crud.searchBtn") }}
            </div>
            <div class="default-btn" @click="resetForm()">
              {{ $t("product.reset") }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div class="primary-btn default-btn" @click="addActive()">新增</div>
        <div class="green-btn default-btn" @click="offlineRow(null, true)">
          批量下架
        </div>
      </div>
      <div class="table-con">
        <div v-if="dataList.length === 0" class="empty-text">
          {{ $t("user.noData") }}
        </div>
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <!-- select -->
          <el-table-column
            fixed
            type="selection"
            :selectable="checkSelectable"
            width="55"
          ></el-table-column
          >x
          <el-table-column
            fixed
            type="index"
            label="序号"
            prop="index"
            align="center"
            width="60"
          />
          <el-table-column
            fixed
            label="活动名称"
            prop="activityName"
            align="center"
            width="120"
          />
          <el-table-column
            label="促销类型"
            prop="activityMarketTypeName"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="活动类型"
            prop="activityBusinessState"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>
                {{ row.activityBusinessState == 1 ? "平台活动" : "商户活动" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="activityRelationshipState"
            align="center"
            label="与其他活动关系"
            width="200"
          >
            <template slot-scope="{ row }">
              <span>
                {{ row.activityRelationshipState == 1 ? "互斥" : "叠加" }}
              </span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="" align="center" label="适用范围">
          </el-table-column> -->
          <el-table-column
            prop="activityOnlineState"
            width="180"
            label="状态"
            align="center"
          >
            <template slot-scope="{ row }">
              <!-- 0进行中1待开始2下架3结束 -->
              <span :class="`status-${row.activityOnlineState}`">
                {{
                  [
                    "进行中",
                    "待开始",
                    "已下架",
                    "已结束",
                    "待审核",
                    "审核通过",
                    "驳回",
                  ][row.activityOnlineState]
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="activityTime"
            label="活动时间"
            align="center"
            width="200"
          >
            <template slot-scope="{ row }">
              <span>{{ mapViewActiveTime(row) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="参与商户数"
            prop="merchantCount"
            align="center"
            width="200"
          />
          <el-table-column
            label="活动销售额"
            prop="activityAmount"
            align="center"
            width="200"
          />
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            width="200"
          >
            <template slot-scope="scope">
              <div class="text-btn-con">
                <div
                  class="text-btn default-btn"
                  @click.stop="editActive(scope.row.id, 'edit')"
                  v-if="
                    (scope.row.activityOnlineState == 0 ||
                      scope.row.activityOnlineState == 1 ||
                      scope.row.activityOnlineState == 3) &&
                    scope.row.activityBusinessState == 1
                  "
                >
                  编辑
                </div>

                <div
                  class="text-btn default-btn"
                  @click.stop="lookActive(scope.row.id, 'readonly')"
                >
                  查看
                </div>
                <div
                  class="text-btn default-btn black"
                  @click.stop="offlineRow(scope.row)"
                  v-if="
                    (scope.row.activityOnlineState == 0 ||
                      scope.row.activityOnlineState == 1) &&
                    scope.row.activityBusinessState == 1
                  "
                  v-show="scope.row.activityOnlineState != 3"
                >
                  下架
                </div>

                <div
                  class="text-btn default-btn"
                  @click.stop="offlineRow(scope.row, null, 0)"
                  v-if="
                    scope.row.activityOnlineState == 2 &&
                    scope.row.activityBusinessState == 1
                  "
                  v-show="scope.row.activityOnlineState != 3"
                >
                  上架
                </div>

                <div
                  class="default-btn text-btn dimission"
                  @click.stop="delRow(scope.row.id)"
                  v-if="scope.row.activityBusinessState == 1"
                >
                  删除
                </div>
              </div>
            </template>
          </el-table-column>
          <div slot="empty">&nbsp;</div>
        </el-table>
      </div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { _types, _weeks, _days } from "./promotionMethodComps/definition";
export default {
  data() {
    return {
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      useTypes: _types,
      useWeeks: _weeks,
      useDays: _days,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      searchForm: {
        activityTimeState: "",
      },
      dataList: [],
      multipleSelection: [],
      timer: [],
      timePickerValueByDay: null,
      timePickerValueByWeek: null,
      timePickerValueByMonth: null,

      checkboxGroups: [],

      timeRadio: [
        {
          label: "今天",
          value: 1,
        },
        {
          label: "昨天",
          value: 2,
        },
      ],
    };
  },
  mounted() {
    this.getActiveList();
  },
  methods: {
    checkSelectable(row) {
      return (
        row.activityBusinessState != 2 &&(
        row.activityOnlineState == 0 ||
        row.activityOnlineState == 1 ||
        row.activityOnlineState == 5)
      );
    },
    mapViewActiveTime(row) {
      function mapWeekDay(str) {
        if (!str) return "";
        let weekTexts = [
          "",
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六",
          "周日",
        ];
        return str
          .split(",")
          .sort()
          .map((m) => ` ${weekTexts[m]} `);
      }
      if (row.activityTimeState == 1) {
        if (row.activityTimeCycleState == 0) {
          return `每天 ${row.activityCycleStartTime}~${row.activityCycleEndTime}`;
        }
        if (row.activityTimeCycleState == 1) {
          return `每周 ${mapWeekDay(row.weekDays)} ${
            row.activityCycleStartTime
          }~${row.activityCycleEndTime}`;
        }
        if (row.activityTimeCycleState == 2) {
          return `每月${row.activityTimeNum}号 ${row.activityCycleStartTime}~${row.activityCycleEndTime}`;
        }
      }
      return `${row.activityStartTime} ~ ${row.activityEndTime}`;
    },
    changeTimePickerByDay(e) {
      console.log(this.timePickerValueByDay);
      this.setSearchFormStartOrEnd(this.timePickerValueByDay);
    },
    changeTimePickerByWeek(e) {
      console.log(this.timePickerValueByWeek);
      this.setSearchFormStartOrEnd(this.timePickerValueByWeek);
    },
    changeTimePickerByMonth(e) {
      console.log(this.timePickerValueByMonth);
      this.setSearchFormStartOrEnd(this.timePickerValueByMonth);
    },
    setSearchFormStartOrEnd(e) {
      this.searchForm.activityCycleStartTime = e[0];
      this.searchForm.activityCycleEndTime = e[1];
    },
    // 切换周期 日期
    changeActivityTimeState() {
      this.clearTimeKeys();
      this.timer = [];
      this.timePickerValueByDay = null;
      this.timePickerValueByWeek = null;
      this.timePickerValueByMonth = null;
    },
    // 周期内切换 天 周 月
    changeActivityTimeCycleState() {
      console.log(this.searchForm.activityTimeCycleState);
      if (this.searchForm.activityTimeCycleState == "0") {
        this.timePickerValueByWeek = null;
        this.timePickerValueByMonth = null;
      } else if (this.searchForm.activityTimeCycleState == "1") {
        this.timePickerValueByDay = null;
        this.timePickerValueByMonth = null;
      } else if (this.searchForm.activityTimeCycleState == "2") {
        this.timePickerValueByDay = null;
        this.timePickerValueByWeek = null;
      }
      this.checkboxGroups = [];
      delete this.searchForm.activityTimeWeekNum;
      delete this.searchForm.activityTimeMonthNum;
    },
    // 选择多选一周
    changeCheckboxGroups() {
      this.searchForm.activityTimeWeekNum = this.checkboxGroups;
    },
    getActiveList() {
      this.$http({
        url: this.$http.adornUrl("/platform/activity/page"),
        method: "get",
        params: this.$http.adornParams(
          Object.assign(
            {
              current: this.page.currentPage || 1,
              size: this.page.pageSize || 10,
            },
            this.searchForm
          )
        ),
      }).then(({ data }) => {
        if (data) {
          this.dataList = data.records;
          this.page.total = data.total;
        }
      });
    },
    createTimeChange() {
      // 处理 searchForm 和 endTime
      if (!this.timer || this.timer.length === 0) {
        this.clearTimeKeys();
      } else {
        this.searchForm.activityStartTime = this.timer[0];
        this.searchForm.activityEndTime = this.timer[1];
        delete this.searchForm.activityCycleStartTime;
        delete this.searchForm.activityCycleEndTime;
      }
      console.log("this.searchForm", this.searchForm);
    },
    clearTimeKeys() {
      delete this.searchForm.activityStartTime;
      delete this.searchForm.activityEndTime;
      delete this.searchForm.activityCycleStartTime;
      delete this.searchForm.activityCycleEndTime;
    },
    // 分页每页多少条
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getActiveList();
    },
    // 分页当前第几页
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getActiveList();
    },
    // 搜索
    handleSearch() {
      this.getGoodsListMessage("search");
    },
    addActive() {
      this.$router.push("/platform-specialOffer/activity-types");
    },
    // 多选
    handleSelectionChange(val) {
      console.log("multipleSelection", val);
      this.multipleSelection = val;
    },
    refreshChange() {
      this.page = {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      };
      this.searchForm = {};
      this.getActiveList();
    },
    // 点击查询
    searchChange() {
      this.page.currentPage = 1;
      console.log("this.searchForm", this.searchForm);
      this.getActiveList();
    },
    resetForm() {
      this.searchForm = {
        activityTimeState: "",
      };
      this.timer = [];
      this.timePickerValueByDay = null;
      this.timePickerValueByWeek = null;
      this.timePickerValueByMonth = null;
    },
    editActive(id, action) {
      this.$router.push({
        path: "/platform-specialOffer/create-activity",
        query: {
          id: id,
          action: action,
        },
      });
    },
    lookActive(id, action) {
      this.$router.push({
        path: "/platform-specialOffer/audit-info",
        query: {
          id: id,
          action: action,
        },
      });
    },
    offlineRow(row, more = false, activityOnlineState = 2) {
      if (more) {
        if (this.multipleSelection.length === 0) {
          this.$message({
            message: "请选择要下架的活动",
            type: "warning",
            duration: 1500,
          });
          return;
        }
      }
      this.$confirm(
        `确定${
          more
            ? "批量" + (activityOnlineState == 2 ? "下架" : "上架") + "已选中的"
            : (activityOnlineState == 2 ? "下架" : "上架") + "该"
        }活动吗？`,
        this.$i18n.t("remindPop.remind"),
        {
          confirmButtonText: this.$i18n.t("remindPop.confirm"),
          cancelButtonText: this.$i18n.t("remindPop.cancel"),
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/platform/activity/batchUpdateCheckState"),
          method: "get",
          params: this.$http.adornParams({
            ids: more
              ? this.multipleSelection.map((item) => item.id)
              : [row.id],
            activityOnlineState: activityOnlineState, // 0进行中 1待开始 2下架 3结束
          }),
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t("remindPop.succeeded"),
            type: "success",
            duration: 1500,
            onClose: () => {
              if (this.page.currentPage > 1 && this.dataList.length === 1) {
                this.page.currentPage--;
              }
              this.getActiveList();
            },
          });
        });
      });
    },
    delRow(id) {
      this.$confirm(
        this.$i18n.t("seckill.isDeleOper"),
        this.$i18n.t("remindPop.remind"),
        {
          confirmButtonText: this.$i18n.t("remindPop.confirm"),
          cancelButtonText: this.$i18n.t("remindPop.cancel"),
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/platform/activity/updateIsDelete/" + id),
          method: "delete",
        }).then(({ data }) => {
          this.$message({
            message: this.$i18n.t("remindPop.succeeded"),
            type: "success",
            duration: 1500,
            onClose: () => {
              if (this.page.currentPage > 1 && this.dataList.length === 1) {
                this.page.currentPage--;
              }
              this.getActiveList();
            },
          });
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.mod-user {
  .tips .text {
    color: #ff0000;
  }

  ::v-deep .el-table__fixed {
    height: auto !important;
    bottom: 16px !important;

    &::before {
      background-color: transparent !important;
    }
  }

  ::v-deep .el-table__fixed-right {
    height: auto !important;
    bottom: 16px !important;

    &::before {
      background-color: transparent !important;
    }
  }
}

.TagS {
  margin-right: 10px !important;
}

.table-con {
  position: relative;
}

.empty-text {
  position: absolute;
  z-index: 4;
  top: 50%;
  left: 50%;
  color: #909399;
}

::v-deep .export-load {
  top: -50% !important;
}

::v-deep
  .el-select
  .el-select__tags
  > span
  > .el-tag.el-tag--info:nth-last-child(2) {
  max-width: 120px;
}

.dimission {
  color: red;
}

.black {
  color: black;
}

.period-panel {
  width: 705px;
  background: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eeeeee;
  box-sizing: border-box;
  padding: 0 10px;
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
  .period-line {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eeeeee;
    min-height: 40px;
    box-sizing: border-box;
    padding: 4px 0;

    &:last-child {
      border: none;
    }

    .time-picker-2 {
      margin-top: 4px;
    }
  }
}
.time-picker-3-week {
  margin-top: 10px;
  width: 385px;
}

.flex {
  display: flex;
}
.status-0 {
  color: #4dc97c;
}
.status-1 {
  color: #ff9b3a;
}
</style>
